package cn.com.gzheroli.bfw.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.pojo.base.TSFunction;
import cn.com.gzheroli.bfw.pojo.base.TSRole;
import cn.com.gzheroli.bfw.pojo.base.TSRoleFunction;
import cn.com.gzheroli.bfw.pojo.base.TSRoleUser;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.mapper.RoleMapper;
import cn.com.gzheroli.core.common.mapper.UserMapper;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboBox;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.SetListSort;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.service.bfw.RoleService;
import cn.com.gzheroli.tag.vo.easyui.TreeGridModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Service("roleService")
public class RoleServiceImpl  implements RoleService  {

	private static final Logger logger = Logger
			.getLogger(RoleServiceImpl.class);
	
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private SystemService systemService;
	@Resource
	private CommonService commonService;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	  private TSDataruleService dataruleService;
	public List<TSUser> getTsUserByRoleId(String roleId) {
		Map para=new HashMap();
		para.put("roleId", roleId);
		List<TSUser> userList=userMapper.getUserListByRole(para);
		return userList;
	}
	public List<Map> getRoles(Map datamap) {
		
		return roleMapper.getRoles(datamap);
	}

	public Long getRolesAcount(Map datamap) {
		return roleMapper.getRolesAcount(datamap);
	}
	@Override
	public List<Map<String,Object>> getOperationList(Map dataMap) {
		// TODO Auto-generated method stub
		return roleMapper.getOperationList(dataMap);
	}
	@Override
	public Long getOperationAcount(Map dataMap) {
		// TODO Auto-generated method stub
		return roleMapper.getOperationAcount(dataMap);
	}
	public List<Map<String,Object>> getAllRoleFunctionList(Map dataMap){
		List<Map<String,Object>> roleFuncList=new ArrayList<Map<String,Object>>();
		List<Map<String,String>> roleFirstFuncList=roleMapper.getRoleFunctionList(dataMap);
		for(Map roleFuncMap:roleFirstFuncList){
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("pid", roleFuncMap.get("id"));
			paraMap.put("roleId", dataMap.get("roleId"));
			List<Map<String,String>> subRoleFuncList=getSubRoleFuncList(paraMap);
			roleFuncMap.put("children", subRoleFuncList);
			roleFuncList.add(roleFuncMap);
		}
		return roleFuncList;
	}
	public List<Map<String,String>> getSubRoleFuncList(Map dataMap){
		List<Map<String,String>> roleFuncList=new ArrayList<Map<String,String>>();
		List<Map<String,String>> roleFirstFuncList=roleMapper.getRoleFunctionList(dataMap);
		for(Map roleFuncMap:roleFirstFuncList){
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("pid", roleFuncMap.get("id"));
			paraMap.put("roleId", dataMap.get("roleId"));
			List<Map<String,String>> subRoleFuncList=getSubRoleFuncList(paraMap);
			roleFuncMap.put("children", subRoleFuncList);
			roleFuncList.add(roleFuncMap);
		}
		return roleFuncList;
	}
	public List<Map<String,Object>> getUserRoles(Map params) {
		
		String sql="select ru.ID,r.ROLE_NAME,r.ROLE_CODE,ru.DEPART_NAME  from T_S_ROLE r,T_S_ROLE_USER ru where r.ID=ru.ROLE_ID  and ru.USER_ID=#{userId}";
		if(params.containsKey("roleCodes")){
			String roleCodes=params.get("roleCodes")==null?"":params.get("roleCodes").toString();
			if(!roleCodes.equals("")){
				roleCodes="'"+roleCodes.replace(",", "','")+"'";
				params.remove("roleCodes");
				params.put("roleCodes", roleCodes);
				sql=sql+" and r.ROLE_CODE in (${roleCodes})";
			}
		}
		return commonService.findForJdbcMap(sql, params);
	}
	public Long getUserRolesCount(Map params) {
		
		String sql="select count(r.ID)  from T_S_ROLE r,T_S_ROLE_USER ru where r.ID=ru.ROLE_ID  and ru.USER_ID=#{userId}";
		if(params.containsKey("roleCodes")){
			String roleCodes=params.get("roleCodes")==null?"":params.get("roleCodes").toString();
			if(!roleCodes.equals("")){
				roleCodes="'"+roleCodes.replace(",", "','")+"'";
				params.remove("roleCodes");
				params.put("roleCodes", roleCodes);
				sql=sql+" and r.ROLE_CODE in (${roleCodes})";
			}
		}
			
		return commonService.getCountForJdbc(sql, params);
	}
	public List<ComboBox> getRoleList(String userId){
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		String sql="select r.ID,r.ROLE_NAME,ru.USER_ID from T_S_ROLE r left joinT_S_ROLE_USER ru on  r.ID=ru.ROLE_ID  and ru.USER_ID=#{userId}";
		//List<Map<String,Object>> roleList=jdbcDao.findForJdbc(sql, userId);
		Map para=new HashMap();
		para.put("userId", userId);
		List<Map<String,Object>> roleList=commonService.findForJdbc(sql, para);
		for(Map role:roleList){
			ComboBox box = new ComboBox();
			box.setId(role.get("id").toString());
			box.setText(role.get("roleName").toString());
			if(role.get("userId")!=null)
				box.setSelected(true);
			else
				box.setSelected(false);
			comboBoxs.add(box);
		}
		return comboBoxs;
	}
	@Override
	public List<Map<String, Object>> getUserNotRoles(Map datamap,int page,int rows) {
		String userid=datamap.get("userId").toString();
		String roleCode=datamap.get("roleCode")==null?"":datamap.get("roleCode").toString();
		String roleName=datamap.get("roleName")==null?"":datamap.get("roleName").toString();
		String sql="select r.ID,r.ROLE_NAME,r.ROLE_CODE from T_S_ROLE r left join T_S_ROLE_USER ru on r. ID = ru.ROLE_ID AND ru.USER_ID =#{userId} where 1=1  ";//ru.ROLE_ID is null
		if(roleCode!=null&&!roleCode.trim().equals(""))
			sql=sql+" and r.ROLE_CODE like '%"+roleCode+"%'";
		if(roleName!=null&&!roleName.trim().equals(""))
			sql=sql+" and r.ROLE_NAME like '%"+roleName+"%'";
		Map para=new HashMap();
		para.put("userId", userid);
		return commonService.findForJdbcPage(sql, Map.class, para, page, rows);
		//return jdbcDao.findForJdbcParam(sql, page, rows, userid);
	}
	@Override
	public Long getUserNotRolesCount(Map datamap) {
		String userId=datamap.get("userId").toString();
		String roleCode=datamap.get("roleCode")==null?"":datamap.get("roleCode").toString();
		String roleName=datamap.get("roleName")==null?"":datamap.get("roleName").toString();
		String sql="select count(1) from T_S_ROLE r left join T_S_ROLE_USER ru on r. ID = ru.ROLE_ID AND ru.USER_ID =#{userId} where 1=1 ";//ru.ROLE_ID is null
		if(roleCode!=null&&!roleCode.trim().equals(""))
			sql=sql+" and r.ROLE_CODE like '%"+roleCode+"%'";
		if(roleName!=null&&!roleName.trim().equals(""))
			sql=sql+" and r.ROLE_NAME like '%"+roleName+"%'";
		Map para=new HashMap();
		para.put("userId", userId);
		Long total=commonService.getCountForJdbc(sql, para);
		return total;
	}
	public List<ComboTree> getAllAuthorityList(Map dataMap){
		//List<Map<String,Object>> roleFuncList=new ArrayList<Map<String,Object>>();
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		List<Map<String,String>> roleFirstFuncList=roleMapper.getRoleFunctionList(dataMap);
		for(Map roleFuncMap:roleFirstFuncList){
			ComboTree comboTree=new ComboTree();
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("pid", roleFuncMap.get("id"));
			paraMap.put("roleId", dataMap.get("roleId"));
			List<ComboTree> children=getSubAuthorityList(paraMap);
			//roleFuncMap.put("children", subRoleFuncList);
			//roleFuncList.add(roleFuncMap);
			comboTree.setChecked(Boolean.valueOf(roleFuncMap.get("checked").toString()));
			comboTree.setChildren(children);
			comboTree.setId(roleFuncMap.get("id").toString());
			comboTree.setState(roleFuncMap.get("state")==null?"":roleFuncMap.get("state").toString());
			comboTree.setText(roleFuncMap.get("text").toString());
			Map attributes=new HashMap();
			if(roleFuncMap.get("operationCode")!=null){
				attributes.put("operationCode", roleFuncMap.get("operationCode").toString());
			}
			comboTree.setAttributes(attributes);
			comboTrees.add(comboTree);
		}
		return comboTrees;
	}
	public List<ComboTree> getSubAuthorityList(Map dataMap){
		//List<Map<String,String>> roleFuncList=new ArrayList<Map<String,String>>();
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		List<Map<String,String>> roleFirstFuncList=roleMapper.getRoleFunctionList(dataMap);
		for(Map roleFuncMap:roleFirstFuncList){
			ComboTree comboTree=new ComboTree();
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("pid", roleFuncMap.get("id"));
			paraMap.put("roleId", dataMap.get("roleId"));
			/*List<Map<String,String>> subRoleFuncList=getSubRoleFuncList(paraMap);
			roleFuncMap.put("children", subRoleFuncList);
			roleFuncList.add(roleFuncMap);*/
			List<ComboTree> children=getSubAuthorityList(paraMap);
			//roleFuncMap.put("children", subRoleFuncList);
			//roleFuncList.add(roleFuncMap);
			comboTree.setChecked(Boolean.valueOf(roleFuncMap.get("checked").toString()));
			comboTree.setChildren(children);
			comboTree.setId(roleFuncMap.get("id").toString());
			comboTree.setState(roleFuncMap.get("state")==null?"":roleFuncMap.get("state").toString());
			comboTree.setText(roleFuncMap.get("text").toString());
			Map attributes=new HashMap();
			if(roleFuncMap.get("operationCode")!=null){
				attributes.put("operationCode", roleFuncMap.get("operationCode").toString());
			}
			comboTree.setAttributes(attributes);
			comboTrees.add(comboTree);
		}
		return comboTrees;
	}
	public AjaxJson updateAuthority(String operations,String roleId,String rolefunction){
		AjaxJson j=new AjaxJson();
		Map<String,String> operationsMap=new HashMap();
		if(operations!=null&&!operations.trim().equals("")){
			JSONArray arr=JSONArray.fromObject(operations);
			Iterator<JSONObject> it = arr.iterator();
			while (it.hasNext()) {
	            JSONObject obj = (JSONObject) it.next();
				operationsMap.put(obj.getString("id"), obj.getString("value"));
			}
		}
		
		
		commonService.executeSQL("delete from T_S_ROLE_FUNCTION  where ROLE_ID='"+ roleId+"'");
		String[] roleFunctions = null;
		if (rolefunction != "") {
			roleFunctions = rolefunction.split(",");
			for (String funcId : roleFunctions) {
				TSRoleFunction rf = new TSRoleFunction();
				rf.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
				rf.setFunctionId(funcId);
				
				String operationCodes=operationsMap.get(funcId);
				rf.setOperation(operationCodes);
				rf.setRoleId(roleId);
				this.commonService.save(rf);
			}
		}
		j.setSuccess(true);
		j.setMsg("保存成功");
		return j;
	}
	public AjaxJson deleteRoleUser(String roleId,String userids){
		AjaxJson j = new AjaxJson();
		
		for (String id : userids.split(",")) {
			String sql = "delete from T_S_ROLE_USER t where t.role_id=? and t.user_id =? ";
			commonService.executeSql(sql, roleId, id);
		}
		j.setMsg("删除角色用户成功");
		j.setSuccess(true);
		return j;
	}
	public AjaxJson updateOperation(String roleId,String functionId,String operationcodes){
		AjaxJson j = new AjaxJson();
		Map para=new HashMap();
		para.put("roleId", roleId);
		para.put("functionId", functionId);
		String sql="select * from T_S_ROLE_FUNCTION where ROLE_ID=#{roleId} and FUNCTION_ID=#{functionId}";
		
		List<TSRoleFunction> rFunctions = commonService.findByQueryString(sql, TSRoleFunction.class, para);
		if (null != rFunctions && rFunctions.size() > 0) {
			TSRoleFunction tsRoleFunction = rFunctions.get(0);
			tsRoleFunction.setOperation(operationcodes);
			commonService.update(tsRoleFunction);
		}else{
			TSRoleFunction tsRoleFunction=new TSRoleFunction();
			tsRoleFunction.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
			tsRoleFunction.setFunctionId(functionId);
			tsRoleFunction.setOperation(operationcodes);
			tsRoleFunction.setRoleId(roleId);
			commonService.save(tsRoleFunction);
		}
		j.setSuccess(true);
		j.setMsg("按钮权限更新成功");
		return j;
	}
	public AjaxJson getOperationListForFunction(TSUser user,String functionId,String roleId){
		AjaxJson j=new AjaxJson();
		Map retMap=new HashMap();
		Map dataMap=new HashMap();
		dataMap.put("functionId", functionId);
		List<Map<String,Object>> operationList=this.getOperationList(dataMap);
		//Set<String> operationCodes = systemService.getOperationCodesByRoleIdAndFunctionId(roleId, functionId);
		Map para=new HashMap();
		para.put("functionId", functionId);
		para.put("roleId", roleId);
		String sql="select OPERATION from T_S_ROLE_FUNCTION r where r.ROLE_ID=#{roleId} and r.FUNCTION_ID=#{functionId}";
		//String authSql=dataruleService.genSqlByModuleName("authUserSql","bu",user);	
		//dataMap.put("authSql", authSql);
		List operationCodes=commonService.findByQueryString(sql, String.class, para);
		retMap.put("operationList", operationList);
		retMap.put("operationcodes", operationCodes);
		retMap.put("functionId", functionId);
		j.setObj(retMap);
		j.setSuccess(true);
		j.setMsg("获取成功");
		return j;
	}
	public void savep(String roleId, String functionId, String ids){
		Map para=new HashMap();
		para.put("roleId", roleId);
		para.put("functionId", functionId);
		String sql="select * from T_S_ROLE_FUNCTION where ROLE_ID=#{roleId} and FUNCTION_ID=#{functionId}";
		
		List<TSRoleFunction> rFunctions = commonService.findByQueryString(sql, TSRoleFunction.class, para);
		if (rFunctions.size() > 0) {
			TSRoleFunction roleFunction = rFunctions.get(0);
			roleFunction.setOperation(ids);
			commonService.update(roleFunction);
		}
	}
	public List<TreeGrid> getOperate(TreeGrid treegrid,String roleId,TSUser user){
		Map para=new HashMap();
		String sql="select * from T_S_FUNCTION ";
		if (treegrid.getId() != null) {
			para.put("functionId", treegrid.getId());
			sql=sql+" and PARENT_ID=#{functionId}";
		}
		if (treegrid.getId() == null) {
			para.put("functionId", null);
		}
		//String authSql=dataruleService.genSqlByModuleName("authUserSql","bu",user);	
		//para.put("authSql", authSql);
		List<TSFunction> functionList =commonService.findByQueryString(sql, TSFunction.class, para);
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		Collections.sort(functionList, new SetListSort());
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setRoleid(roleId);
		treeGrids = commonService.treegrid(functionList, treeGridModel);
		return treeGrids;
	}
}
